package com.aerilys.taskboard.client.views.implementation;

import com.aerilys.taskboard.client.NoteService;
import com.aerilys.taskboard.client.NoteServiceAsync;
import com.aerilys.taskboard.client.places.GeneralViewPlace;
import com.aerilys.taskboard.client.views.AddTaskView;
import com.aerilys.taskboard.client.views.DetailsView.Presenter;
import com.aerilys.taskboard.shared.Note;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.ButtonElement;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.TextAreaElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Widget;

public class AddTaskViewImpl extends Composite implements AddTaskView
{

  private static AddTaskViewImplUiBinder uiBinder = GWT.create(AddTaskViewImplUiBinder.class);

  interface AddTaskViewImplUiBinder extends UiBinder<Widget, AddTaskViewImpl>
  {
  }

  private final NoteServiceAsync noteService = GWT.create(NoteService.class);

  @UiField
  InputElement taskName;

  @UiField
  TextAreaElement taskDescription;

  @UiField
  Button button;

  @UiHandler("button")
  void onButtonClick(ClickEvent event)
  {
    Note note = new Note();
    note.setNom(taskName.getValue());
    note.setDescription(taskDescription.getValue());

    noteService.greetServer(note, new AsyncCallback<String>()
    {
      @Override
      public void onSuccess(String result)
      {
        Window.alert("Tache ajoutee !");
        backToHome();
      }

      @Override
      public void onFailure(Throwable caught)
      {
        Window.alert("Erreur lors de l'ajout de la tache : " + caught.getMessage());
      }
    });

  }

  public AddTaskViewImpl()
  {
    initWidget(uiBinder.createAndBindUi(this));
  }

  private Presenter presenter;

  public AddTaskViewImpl(String firstName)
  {
    initWidget(uiBinder.createAndBindUi(this));
  }

  @Override
  public void setPresenter(Presenter presenter)
  {
    this.presenter = presenter;
  }

  public void backToHome()
  {
    this.presenter.goTo(new GeneralViewPlace("Accueil"));
  }

}
